package Pruebas.Manolo;


import com.google.common.collect.ForwardingMultiset;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.primitives.Ints;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

enum EntryComp implements Comparator<Multiset.Entry<?>> {
    DESCENDING {
        @Override
        public int compare(final Multiset.Entry<?> a, final Multiset.Entry<?> b) {
            return Ints.compare(b.getCount(), a.getCount());
        }
    },
    ASCENDING {
        @Override
        public int compare(final Multiset.Entry<?> a, final Multiset.Entry<?> b) {
            return Ints.compare(a.getCount(), b.getCount());
        }
    },
}

public class FreqSortMultiSet<E> extends ForwardingMultiset<E> {
    Multiset<E> delegate;
    EntryComp comp;

    public FreqSortMultiSet(Multiset<E> delegate, boolean ascending) {
        this.delegate = delegate;
        if (ascending)
            this.comp = EntryComp.ASCENDING;
        else
            this.comp = EntryComp.DESCENDING;
    }

    @Override
    protected Multiset<E> delegate() {
        return delegate;
    }

    @Override
    public Set<Entry<E>> entrySet() {
        TreeSet<Entry<E>> sortedEntrySet = new TreeSet<>(comp);
        sortedEntrySet.addAll(delegate.entrySet());
        return sortedEntrySet;
    }
    
    public E primero(){
        return (E) this.elementSet().toArray()[0];
    }

    @Override
    public Set<E> elementSet() {
        Set<E> sortedEntrySet = new LinkedHashSet<>();
        for (Entry<E> en : entrySet())
            sortedEntrySet.add(en.getElement());
        return sortedEntrySet;
    }

    public static <E> FreqSortMultiSet<E> create(boolean ascending) {
        return new FreqSortMultiSet<>(HashMultiset.<E> create(), ascending);
    }

    
    
      public static void main(String[] args) {
        FreqSortMultiSet<String> s = FreqSortMultiSet.create(false);
        s.add("Hello");
        s.add("Hello");
        s.setCount("World", 8);
        s.setCount("Bye", 5);
        System.out.println(s.entrySet());
        System.out.println(s.primero());
        //System.out.println(s.);
    }

}